# -*- coding: utf-8 -*-
__author__ = 'alex'


import MySQLdb
from commonRoutine import *

DB_PREFIX = "en_"
TABLE_PAGE = DB_PREFIX + "page"
TABLE_TEMPLATELINKS = DB_PREFIX + "templatelinks"
TABLE_CATEGORYLINKS = DB_PREFIX + "categorylinks"
TABLE_INFOBOX = DB_PREFIX + "infobox"
TABLE_INFOBOX_CATEGORIES = DB_PREFIX + "infobox_categories"
TABLE_INFOBOX_ATTRIBUTES = DB_PREFIX + "infobox_attrib"
ERROR_DUBLICATE_ENTRY = 1062


NAMESPACE_CATEGORY = "14"
NAMESPACE_TEMPLATE = "10"

def quoted(string):
    return "\"" + string + "\""


class DBWriter(object):
    def __init__(self):
        #self._regexp = re.compile(u"{{{([-A-Za-zА-Яа-я0-9 _\t]*?)\|.*?}}}")
        self._columns = ['ia_of', 'ia_name']

        self._connection = MySQLdb.connect(host = 'localhost',
                                           user = 'alex',
                                           db =   'ruwiki')

        self._connection.set_character_set('utf8')
        #self._cursor = self._connection.cursor()


    def getInfPageDescription(self):
        infobox_set = set()

        query = 'SELECT inf_id from ' + TABLE_INFOBOX

        cursor = self._connection.cursor()
        try:
            cursor.execute(query)
        except MySQLdb.Error, e:
            print "in getInfPageDesriction. Cant` read infoboxes id"
            raise

        for infobox in cursor.fetchall():
            infobox_set.add(infobox[0])

        cursor.close()

        inf_page_relation = {}

        for infobox in infobox_set:
            self.getOneInfDescription(infobox, ONE_INFOBOX_PAGE_LIMIT, inf_page_relation)

        return inf_page_relation

    def write(self, infobox):
        for attrib in infobox[1]:
            values = [infobox[0].encode("utf-8"), quoted(attrib.encode("utf-8"))]
            self.writeToDB(TABLE_INFOBOX_ATTRIBUTES, values)

    """
    #TODO: test this. All should be unicode, even numbers
    def write(self, page):
        if page._id not in self._infoboxes:
            print page._id, "is not in infobox set"
            return

        attribSet = set()

        for attrib in self._regexp.findall(page._text):
            attribSet.add(attrib.strip())

        for attrib in attribSet:
            values = [page._id.encode("utf-8"), quoted(attrib.encode("utf-8"))]
            self.writeToDB(TABLE_INFOBOX_ATTRIBUTES, values)
    """

    def writeToDB(self, tableName, values):
        query = "INSERT INTO " + tableName + \
                "(" + ", ".join(self._columns) + ")" \
                " VALUES ( " +  ", ".join(values) + " )"
        cursor = self._connection.cursor()
        try:
            cursor.execute(query)
            cursor.close()
            self._connection.commit()
        except MySQLdb.Error, e:
        #it may be OK if dublicate. let it be processed higher
            if e.args[0] == ERROR_DUBLICATE_ENTRY:
                print "dublicate", values
                cursor.close()
                #raise #TODO: comment this later
                return

            #show some error environment
            print "EXCEPTION in write_to_db"
            print "values = ", values
            #delete unnecessary spaces for pretty report
            refined_query = ' '.join(query.split())
            print "query = ", refined_query
            raise


    def getOneInfDescription(self, inf_id, limit, inf_page_relation):
            #get limit page_title`s for getting their infoboxes attrib later
            query = "SELECT tl_from, page_title, page_id FROM " + \
                    TABLE_PAGE + " INNER JOIN " + TABLE_TEMPLATELINKS + \
                    " ON tl_title = page_title WHERE tl_namespace = " + \
                    NAMESPACE_TEMPLATE + " AND page_id = " + str(inf_id) + \
                    " LIMIT " + str(limit)

            infoboxes = None

            try:
                cursor = self._connection.cursor()
                cursor.execute(query)
                infoboxes = cursor.fetchall()
                cursor.close()
            except MySQLdb.Error, e:
                print "EXCEPTION in getInfDescription"
                #delete unnecessary spaces for pretty report
                refined_query = ' '.join(query.split())
                print "query = ", refined_query
                raise

            #TODO: delete this. It`s only for testing
            if inf_id == 3430420:
                inf_page_relation[u"15881"] = [(u"Infobox_programming_language", u"3430420")]

            #record contains:
            # tl_from - id of page containing infobox (string)
            # page_title - name of infobox (string)
            # page_id - id of infobox (string)
            for record in infoboxes:
                id = unicode(str(record[0]), "utf-8")
                if id not in inf_page_relation:
                    #create list of infoboxes page having this id linked with
                    #it can`t contain more than one but may have link to parent infobox
                    inf_page_relation[id] = []

                #insert new infobox description
                inf_page_relation[id].append(
                    (normalize(unicode(record[1], "utf-8")),
                    unicode(str(record[2]), "utf-8")))




    def __del__(self):
        self._connection.close()

  